package com.yc.yn.service.impl;


import com.yc.yn.constants.Globals;
import com.yc.yn.dao.UserDao;
import com.yc.yn.mapper.UserMapper;
import com.yc.yn.model.TSUser;
import com.yc.yn.support.utils.IdWorker;
import com.yc.yn.support.utils.QRCodeUtils;
import com.yc.yn.support.utils.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class UserServiceImpl extends BaseService<TSUser, String> {

	@Autowired
	private UserDao userDao;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private QRCodeUtils qrCodeUtils;
	@Autowired
	private IdWorker idWorker;

	//测试dao
	public TSUser findCustomer(String id) {
		return userDao.findCustomer(id);
	}

	//测试mapper
	public TSUser testU(String id) {
		return userMapper.testU(id);
	}

	/**
	 * 判断用户名是否存在
	 */
	public TSUser queryUsernameIsExist(String username) {
		return userDao.findByUsername(username);
	}

	/**
	 * 用户注册
	 */
	public TSUser saveUser(TSUser user) {
		String userId = idWorker.nextId();
		String qrCodeUrl = this.uploadQRCode(user, userId);
		user.setQrcode(qrCodeUrl);
		return userDao.save(user);
	}

	/**
	 * 生成二维码并上传
	 * 2020-2-3 17:34:12
	 */
	public String uploadQRCode(TSUser user, String qrCodeId) {
		String uploadPath = ResourceUtil.getConfigByName("uploadPath") + "/"
				+ ResourceUtil.getConfigByName("uploadQrCodePath");
		String realPath = Globals.targetClassPath.getAbsolutePath() + "/static/" + uploadPath;// 文件的绝对路径
		realPath = realPath.replaceAll("%20", " ").replaceAll("!", "");//替换字符
		File file = new File(realPath);
		if (!file.exists()) {
			file.mkdirs();// 创建根目录
		}
		// 为每个用户生成一个唯一的二维码
		String suffix = "/" + qrCodeId + "qrcode.png";
		String qrCodePath = realPath + suffix;
		// yc:[username]
		qrCodeUtils.createQRCode(qrCodePath, "ycChat_qrcode:" + user.getUsername());
//		MultipartFile qrCodeFile = FileUtils.fileToMultipart(qrCodePath);
//		try {
//			assert qrCodeFile != null;
//			qrCodeFile.transferTo(new File(qrCodePath));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		return "/static/" + uploadPath + suffix;
	}

}
